﻿using System.IO;
using System.Runtime.InteropServices;
using System.Text;

namespace FsAddInManager
{
	public class IniFile
	{
		public string FilePath
		{
			get
			{
				return this.m_filePath;
			}
		}

		public IniFile(string filePath)
		{
			this.m_filePath = filePath;
			if (!File.Exists(this.m_filePath))
			{
				FileUtils.CreateFile(this.m_filePath);
				FileUtils.SetWriteable(this.m_filePath);
			}
		}

		public void WriteSection(string iniSection)
		{
			IniFile.WritePrivateProfileSection(iniSection, null, this.m_filePath);
		}

		public void Write(string iniSection, string iniKey, object iniValue)
		{
			IniFile.WritePrivateProfileString(iniSection, iniKey, iniValue.ToString(), this.m_filePath);
		}

		public string ReadString(string iniSection, string iniKey)
		{
			StringBuilder stringBuilder = new StringBuilder(255);
			IniFile.GetPrivateProfileString(iniSection, iniKey, "", stringBuilder, 255, this.m_filePath);
			return stringBuilder.ToString();
		}

		public int ReadInt(string iniSection, string iniKey)
		{
			return IniFile.GetPrivateProfileInt(iniSection, iniKey, 0, this.m_filePath);
		}

		[DllImport("kernel32.dll")]
		private static extern int WritePrivateProfileSection(string lpAppName, string lpString, string lpFileName);

		[DllImport("kernel32", CharSet = CharSet.Auto)]
		private static extern int WritePrivateProfileString(string section, string key, string val, string filePath);

		[DllImport("kernel32")]
		private static extern int GetPrivateProfileInt(string section, string key, int def, string filePath);

		[DllImport("kernel32", CharSet = CharSet.Auto)]
		private static extern int GetPrivateProfileString(string section, string key, string defaultValue, StringBuilder retVal, int size, string filePath);

		private string m_filePath;
	}
}
